<script setup>
import { nextTick, ref } from 'vue';
import { commodityCategoryEditService } from '@/apis/commodity';

const categoryModelRef = ref();
const categoryModel = ref({});

let isGiveupWarning = false;
const handleClose = (done) => {
  // 判断是否有部分表单已经赋值了
  var hasValueProps = Object.keys(categoryModel.value).filter(
    (key) => categoryModel.value[key]
  );
  if (hasValueProps.length > 0) {
    if (!isGiveupWarning) {
      ElMessage.warning('当前的 分类 未保存，放弃保存请再次点击取消');
      isGiveupWarning = true;
      setTimeout(() => {
        isGiveupWarning = false;
      }, 3000);
      return;
    }
  }

  if (done) {
    done();
  } else {
    dialogVisible.value = false;
  }
};

const rules = ref({
  categoryName: [
    {
      required: true,
      message: '请输入 商品分类 名称',
      trigger: 'blur'
    }
  ],
  sortNum: [
    {
      required: true,
      message: '请输入数字',
      trigger: 'blur'
    }
  ]
});

const dialogVisible = ref(false);
const title = ref('');
const open = (model) => {
  nextTick(() => {
    categoryModelRef.value &&
      categoryModelRef.value.clearValidate &&
      categoryModelRef.value.clearValidate();
  });

  dialogVisible.value = true;
  title.value = model.id ? '编辑商品分类' : '新增商品分类';
  categoryModel.value = model;
};

defineExpose({
  open
});

const emit = defineEmits(['finishEdit']);

const onConfirm = async () => {
  await categoryModelRef.value.validate();
  let categoryModelCopy = JSON.parse(JSON.stringify(categoryModel.value));
  let res = await commodityCategoryEditService(categoryModelCopy);
  ElMessage.success(res.msg);
  dialogVisible.value = false;
  emit('finishEdit');
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="30%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="categoryModelRef"
      :model="categoryModel"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="categoryModel.categoryName"></el-input>
      </el-form-item>
      <el-form-item label="排序号" prop="sortNum">
        <el-input-number
          :min="1"
          :precision="0"
          v-model="categoryModel.sortNum"
        ></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onConfirm">确认</el-button>
        <el-button @click="handleClose()"> 取消 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
